package com.bicycle.wxpublic.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.bicycle.common.helper.SignatureHelper;
import com.bicycle.wxpublic.exception.BusinessException;
import com.bicycle.wxpublic.service.WeChatService;
import com.bicycle.wxpublic.vo.WeChatAccessTokenVo;
import com.bicycle.wxpublic.vo.WeChatJsapiSignatureVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;


import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : layne
 * @Date: 2020/8/6
 * @Time: 21:59
 * Description:
 */
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private Environment environment;

    @Override
    public WeChatJsapiSignatureVo jsapiSignature() {
        WeChatJsapiSignatureVo weChatJsapiSignatureVo = new WeChatJsapiSignatureVo();
        WeChatJsapiSignatureVo.JsapiSignatureVo jsapiSignatureVo = new WeChatJsapiSignatureVo.JsapiSignatureVo();


        String appId = environment.getProperty("wxpublic.wx.appId");
        String secret = environment.getProperty("wxpublic.wx.secret");
        String accessTokenUrl = MessageFormat.format(environment.getProperty("wxpublic.wx.url.accessToken"), appId, secret);
        String result = HttpRequest.get(accessTokenUrl).execute().body();
        log.debug(">>>>>>acctoken url get:{}", result);
        JSONObject response = JSONObject.parseObject(result);
        String accessToken = response.getString("access_token");
        String ticketUrl = MessageFormat.format(environment.getProperty("wxpublic.wx.url.ticket"), accessToken);
        result = HttpRequest.get(ticketUrl).execute().body();
        log.debug(">>>>>>ticket url get:{}", result);
        response = JSONObject.parseObject(result);

        Map<String, String> map = new HashMap<>();
        map.put("noncestr", SignatureHelper.generateNonceStr());
        map.put("timestamp", String.valueOf(SignatureHelper.getCurrentTimestamp()));
        map.put("jsapi_ticket", response.getString("ticket"));
        map.put("url", environment.getProperty("wxpublic.wx.url.local"));
        String preSign = SignatureHelper.generatePreSignature(map);
        log.info(">>>>>preSign:{}", preSign);
        map.put("sign", DigestUtils.sha1Hex(preSign));

        jsapiSignatureVo.setAppId(appId);
        jsapiSignatureVo.setNonceStr(map.get("noncestr"));
        jsapiSignatureVo.setSignature(map.get("sign"));
        jsapiSignatureVo.setTimestamp(Long.parseLong(map.get("timestamp")));
        jsapiSignatureVo.setUrl(map.get("url"));

        weChatJsapiSignatureVo.setAccessToken(accessToken);
        weChatJsapiSignatureVo.setWxJsapiSignature(jsapiSignatureVo);
        return weChatJsapiSignatureVo;
    }

    /**
     * 根据微信code获取accesstoken
     *
     * @param code
     * @return
     */
    @Override
    public WeChatAccessTokenVo getWxAccessToken(String code) {
        WeChatAccessTokenVo weChatAccessTokenVo = new WeChatAccessTokenVo();
        String appId = environment.getProperty("wxpublic.wx.appId");
        String secret = environment.getProperty("wxpublic.wx.secret");
        String accessTokenUrl = MessageFormat.format(environment.getProperty("wxpublic.wx.url.accessTokenWeb"), appId, secret, code);
        String result = HttpRequest.get(accessTokenUrl).execute().body();
        log.debug(">>>>>>accessToken web url get:{}", result);
        JSONObject response = JSONObject.parseObject(result);
        if (StringUtils.isBlank(response.getString("openid"))) {
            throw new BusinessException(500, response.getString("errmsg"));
        }
        weChatAccessTokenVo.setAccessToken(response.getString("access_token"));
        weChatAccessTokenVo.setOpenId(response.getString("openid"));
        return weChatAccessTokenVo;
    }
}
